﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Coolite.Ext.Web;
using Newtonsoft.Json.Linq;
using Pap.Web.Modules.Loan.ViewModel;
using Pap.Web.Utils;
using Utils.UIPermission;

namespace Pap.Web.Modules.Loan.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class NewLoanList : BasePage<NewLoanListViewModel>, IPermittedPage
    {
        #region [ Events ]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && !Ext.IsAjaxRequest)
            {
                FillLoansGrid();
            }
        }

        /// <summary>
        /// Handles the Submit event of the Button Submit.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void Btn_Submit(object sender, AjaxEventArgs e)
        {
            var selectedRows = ((RowSelectionModel)grvLoans.SelectionModel.Primary).SelectedRows;
            if (selectedRows.Count > 0)
            {
                string jsonString = e.ExtraParams["grvLoans"];
                JArray jarr = JSON.Deserialize(jsonString) as JArray;

                var selectedLoanIDs = selectedRows.Select(sR => sR.RecordID.ToGuid()).ToArray();
                var selectedLoansData = new Dictionary<Guid, string>();

                for (int i = 0; i < jarr.Count; i++)
                {
                    if (selectedLoanIDs.Contains(jarr[i]["LoanID"].ToString().Trim('"').ToGuid()))
                    {
                        string tempString = "";
                        if (jarr[i]["Notes"] != null)
                            tempString = (jarr[i]["Notes"].ToString().Trim('"'));
                        selectedLoansData.Add(jarr[i]["LoanID"].ToString().Trim('"').ToGuid(), tempString);
                    }
                }

                ViewModel.SubmitLoans(selectedLoansData);


                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.INFO,
                    Title = GetLocalResourceObject("MBLoansSubmitted").ToString(),
                    Modal = true,
                    Message = string.Format("{0} {1}", selectedLoanIDs.Count(), GetLocalResourceObject("MBMSG")),
                    Buttons = MessageBox.Button.OK
                }).Show();

                FillLoansGrid();
            }
        }

        /// <summary>
        /// Handles the Refresh event of the Paging control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Paging_Refresh(object sender, EventArgs e)
        {
            FillLoansGrid();
        }

        /// <summary>
        /// Handles the Command event of the GrvLoans control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void GrvLoans_Command(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["CommandName"].Equals("ViewLoan"))
            {
                this.RedirectFromThisPage("Loan", "CreateLoan", "LoanID=" + e.ExtraParams["LoanID"]);
            }
        }

        /// <summary>
        /// Handles the Click event of the btnBack control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnBack_Click(object sender, AjaxEventArgs e)
        {
            this.RedirectToPreviousPage();
        }
        #endregion

        #region [ Methods ]
        /// <summary>
        /// Fills the loans grid with the new loans.
        /// </summary>
        private void FillLoansGrid()
        {
            storeLoans.DataSource = this.ViewModel.GetNewLoans();
            storeLoans.DataBind();
        }

        /// <summary>
        /// Deletes the selected loans.
        /// </summary>
        [AjaxMethod]
        public void DeleteSelectedLoans()
        {
            try
            {
                SelectedRowCollection selectedRows = (grvLoans.SelectionModel.Primary as RowSelectionModel).SelectedRows;
                List<Guid> selectedLoans = selectedRows.Select(row => row.RecordID.ToGuid()).ToList();
                this.ViewModel.DeleteAllLoans(selectedLoans);
                //---------------------------------------------------------------
                FillLoansGrid();
                grvLoans.Reload();
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Title = GetLocalResourceObject("MBError").ToString(),
                    Message = GetLocalResourceObject("MBCouldntDelete").ToString(),
                    Icon = MessageBox.Icon.ERROR,
                    Buttons = MessageBox.Button.OK
                }).Show();
            }
        }
        #endregion

        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission of viewing this page.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "NewLoanList"; }
        }

        #endregion
    }
}
